package com._54programer.ws.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description
 * 用于检测channel的心跳的handler
 */
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            switch (event.state()){
                case READER_IDLE:
                    //读空闲, 不做处理
                    break;
                case WRITER_IDLE:
                    //写空闲, 不做处理
                    break;
                case ALL_IDLE:
                    //读写空闲被触发, 关闭channel
                    log.warn("读写空闲被触发, " + ctx.channel().id() + ", 强制下线");
                    log.warn("触发前连接数: "+WsServerHandler.clients.size());
                    Channel channel = ctx.channel();
                    channel.close();
                    log.warn("触发后连接数: "+WsServerHandler.clients.size());
                    break;
            }
        }
    }
}
